package com.lyhengtongwl.zqsnews.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aigestudio.wheelpicker.WheelPicker;
import com.alibaba.fastjson.JSONObject;
import com.lyhengtongwl.zqsnews.App;
import com.lyhengtongwl.zqsnews.R;
import com.lyhengtongwl.zqsnews.base.BaseActivity;
import com.lyhengtongwl.zqsnews.base.Constant;
import com.lyhengtongwl.zqsnews.entity.NewsBaseEntity;
import com.lyhengtongwl.zqsnews.entity.UserBo;
import com.lyhengtongwl.zqsnews.net.MyCallback;
import com.lyhengtongwl.zqsnews.net.Task;
import com.lyhengtongwl.zqsnews.utils.BitmapCompressUtils;
import com.lyhengtongwl.zqsnews.utils.FileUtils;
import com.lyhengtongwl.zqsnews.utils.ImRezUtils;
import com.lyhengtongwl.zqsnews.utils.NewsToastUtils;
import com.lyhengtongwl.zqsnews.utils.PermissionUtils;
import com.lyhengtongwl.zqsnews.utils.SPUtils;
import com.lyhengtongwl.zqsnews.utils.ScreenUtil;
import com.lyhengtongwl.zqsnews.utils.TitleBuilder;
import com.lyhengtongwl.zqsnews.widget.CenterDialog;
import com.makeramen.roundedimageview.RoundedImageView;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.shaohui.bottomdialog.BottomDialog;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Response;

import static com.lyhengtongwl.zqsnews.base.Constant.EDIT_NICKNAME;
import static com.lyhengtongwl.zqsnews.base.Constant.PICK_PHOTO_CODE;
import static com.lyhengtongwl.zqsnews.base.Constant.TAKE_PHOTO_CODE;


public class NewsMineInfoActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {
    @BindView(R.id.iv_title_right)
    ImageView ivTitleRight;

    @BindView(R.id.wheelPicker)
    WheelPicker wheelPicker;
    @BindView(R.id.ll_select)
    LinearLayout ll_select;
    @BindView(R.id.vObscuration)
    View vObscuration;
    @BindView(R.id.rl_content)
    RelativeLayout rl_content;
    @BindView(R.id.tv_sex)
    TextView tv_sex;
    @BindView(R.id.tv_nickname)
    TextView tv_nickname;
    @BindView(R.id.im_ivHead)
    RoundedImageView roundedImageView;
    @BindView(R.id.tv_phone)
    TextView tv_phone;
    @BindView(R.id.tv_rz)
    TextView tv_rz;
    private String tvRz;
    private List<String> sexList;
    private String sex = "男";
    private String avatar;
    private String mobile;
    private String nickName;
    private final String[] PERMISSIONS = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,//存储权限
            Manifest.permission.READ_EXTERNAL_STORAGE};

    /**
     * 获取相关权限
     */
    private void getPermission() {
        if (EasyPermissions.hasPermissions(this, PERMISSIONS)) {
            //已经打开权限
            showSelectDialog();
        } else {
            //没有打开相关权限、申请权限
            EasyPermissions.requestPermissions(this, "需要获取您的相册、相机使用权限，否则将无法进行修改图像！", 1, PERMISSIONS);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //回调结果
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        if (perms.size() == 3) {
            showSelectDialog();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        NewsToastUtils.showToast(App.getContext(), "权限已被拒绝，请手动在设置里面打开权限！");
    }


    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void setListen() {
        rl_content.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                vObscuration.setVisibility(View.GONE);
                ll_select.setVisibility(View.GONE);
                return false;
            }
        });
        wheelPicker.setOnWheelChangeListener(new WheelPicker.OnWheelChangeListener() {
            @Override
            public void onWheelScrolled(int offset) {

            }

            @Override
            public void onWheelSelected(int position) {
                tv_sex.setText(sexList.get(position));
                sex = sexList.get(position);
            }

            @Override
            public void onWheelScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void setTitleBarColor() {
        ivTitleRight.setVisibility(View.GONE);
        new TitleBuilder(this).setTitleText(getString(R.string.mineInfo))
                .setLeftIcoListening(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        finish();
                    }
                });
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_new_mineinfo;
    }

    @Override
    public void initView() {
    }

    @Override
    public void initData() {
        nickName = SPUtils.get(App.getContext(), "nickName", "") + "";
        tv_nickname.setText(nickName);
        tvRz = SPUtils.get(App.getContext(), "authStatus", "") + "";
        switch (tvRz) {
            case "0"://未认证
                tv_rz.setText("点击进行实名认证");
                tv_rz.setTextColor(getResources().getColor(R.color.mainBg));
                break;
            case "1"://已认证
                tv_rz.setText("已认证");
                tv_rz.setTextColor(getResources().getColor(R.color.color999));
                break;
        }
        avatar = SPUtils.get(App.getContext(), "avatar", "") + "";
        mobile = SPUtils.get(App.getContext(), "mobile", "") + "";
        if ("".equals(avatar)) {
            Picasso.with(App.getContext()).load(R.drawable.detail_head).into(roundedImageView);
        } else {
            Picasso.with(App.getContext()).load(avatar).into(roundedImageView);
        }
        tv_phone.setText(mobile.replace(mobile.substring(3, 7), "****"));
        sexList = new ArrayList<>();
        sexList.add("男");
        sexList.add("女");
    }

    @Override
    protected void onResume() {
        super.onResume();
        mobile = SPUtils.get(App.getContext(), "mobile", "") + "";
        if (!mobile.equals(""))
            tv_phone.setText(mobile.replace(mobile.substring(3, 7), "****"));
        tvRz = SPUtils.get(App.getContext(), "authStatus", "") + "";
        switch (tvRz) {
            case "0"://未认证
                tv_rz.setText("点击进行实名认证");
                tv_rz.setTextColor(getResources().getColor(R.color.mainBg));
                break;
            case "1"://已认证
                tv_rz.setText("已认证");
                tv_rz.setTextColor(getResources().getColor(R.color.color999));
                break;
        }
    }

    @Override
    protected boolean isStatusBarBlack() {
        return true;
    }

    @OnClick({R.id.rl_sex, R.id.tv_back, R.id.tv_done, R.id.rl_changePhoto, R.id.rl_nickname, R.id.rl_phone, R.id.rl_rz})
    public void onViewClicked(View view) {
        if (ScreenUtil.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.rl_sex://性别
                vObscuration.setVisibility(View.VISIBLE);
                ll_select.setVisibility(View.VISIBLE);
                wheelPicker.setData(sexList);
                break;
            case R.id.tv_back://关闭选择框
                vObscuration.setVisibility(View.GONE);
                ll_select.setVisibility(View.GONE);
                break;
            case R.id.tv_done://修改完成
                vObscuration.setVisibility(View.GONE);
                ll_select.setVisibility(View.GONE);
                break;
            case R.id.rl_changePhoto://修改图像
                getPermission();
                break;
            case R.id.rl_nickname://修改昵称
                startActivityForResult(new Intent(this, NewsChangeNikeNameActivity.class)
                        .putExtra("nickname", nickName), EDIT_NICKNAME);
                break;
            case R.id.rl_phone://换绑手机号
                startActivity(new Intent(this, NewsCheckOldMobileActivity.class));
                break;
            case R.id.rl_rz://实名认证
                if (tvRz.equals("0")) {
                    startActivity(new Intent(this, NewsAuthenticationActivity.class));
                } else {
                    NewsToastUtils.showToast(NewsMineInfoActivity.this, "已经认证过！");
                }
                break;
        }
    }

    /**
     * 选择照片弹窗
     */
    private void showSelectDialog() {
        final BottomDialog bottomDialog;
        bottomDialog = BottomDialog.create(this.getSupportFragmentManager());
        bottomDialog.setViewListener(new BottomDialog.ViewListener() {
            @Override
            public void bindView(View v) {
                //照相
                v.findViewById(R.id.tv_takephoto).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (PermissionUtils.getInstance().checkPermission(NewsMineInfoActivity.this,
                                Manifest.permission.CAMERA)) {
                            File myhead = new File(Constant.DIR_INFO.APP_DIR + "/head.jpg");
                            Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            Uri uri = FileProvider.getUriForFile(NewsMineInfoActivity.this,
                                    getPackageName() + ".provider", myhead);
                            it.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                            startActivityForResult(it, PICK_PHOTO_CODE);
                        } else {
                            PermissionUtils.getInstance().showSystemPermissionsSettingDialog(NewsMineInfoActivity.this);
                        }
                        bottomDialog.dismiss();
                    }
                });
                //选择照片
                v.findViewById(R.id.tv_selectphoto).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent it = new Intent(Intent.ACTION_PICK, null);
                        it.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                        startActivityForResult(it, TAKE_PHOTO_CODE);
                        bottomDialog.dismiss();
                    }
                });

                //取消
                v.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        bottomDialog.dismiss();
                    }
                });

            }
        }).setLayoutRes(R.layout.select_change_image)
                .setDimAmount(0.4f)            // Dialog window dim amount(can change window background color）, range：0 to 1，default is : 0.2f
                .setCancelOutside(true)     // click the external area whether is closed, default is : true
                .setTag("BottomDialog")     // setting the DialogFragment tag
                .show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //选择图片
        if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
            try {
                if (data.getData() != null) {
                    //TODO

                    String path = FileUtils.getFilePath(this, data.getData());//图片路径
//                    String path = "storage/emulated/0/Pictures/Screenshots/"+System.currentTimeMillis()+".jpg";//图片路径
                    Bitmap bm = null;
                    ///storage/emulated/0/Pictures/Screenshots/Screenshot_20190123-214734.jpg
                    File file = new File(path);
                    if (file.exists()) {
                        bm = BitmapFactory.decodeFile(FileUtils.getFilePath(this, data.getData()));
                        bm = BitmapCompressUtils.imageZoom(bm, 50);
                        file = ImRezUtils.saveBitmapFile(bm, path);
                    }
                    //上传图片
                    if (FileUtils.getFilePath(this, data.getData()) != null) {
                        // TODO 上传服务器
                        SPUtils.put(App.getContext(), "head", path);
                        upLoadFile(file, bm);
                    } else {
                        NewsToastUtils.showToast(NewsMineInfoActivity.this, "文件不存在！");
                    }
                } else {
                    Log.e("TAG", "onActivityResult: 为空");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        //拍照
        if (requestCode == PICK_PHOTO_CODE && resultCode == RESULT_OK) {
            try {
                String path = Constant.DIR_INFO.APP_DIR + "/head.jpg";
                File temp = new File(path);
                if (temp.exists()) {
                    // TODO 上传服务器
                    Bitmap bm = BitmapFactory.decodeFile(Constant.DIR_INFO.APP_DIR + "/head.jpg");
                    bm = BitmapCompressUtils.imageZoom(bm, 50);
                    temp = ImRezUtils.saveBitmapFile(bm, path);
                    SPUtils.put(App.getContext(), "head", path);
                    upLoadFile(temp, bm);
                } else {
                    NewsToastUtils.showToast(NewsMineInfoActivity.this, "文件不存在！");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        //修改昵称
        if (requestCode == EDIT_NICKNAME && resultCode == RESULT_OK) {
            assert data != null;
            String nickname = data.getStringExtra("nickname");
            tv_nickname.setText(nickname);
        }
    }


    //插入到数据库
    private void insertData(String avatar) {
        SPUtils.put(App.getContext(), "avatar", avatar);
        String userId = SPUtils.get(App.getContext(), "userId", "") + "";
        String nikeName = SPUtils.get(App.getContext(), "nickName", "") + "";
        UserBo userBo = new UserBo();
        userBo.setAvatar(avatar);
        userBo.setNickname(nikeName);
        userBo.setUserid(userId);
        Task.getApiService().insertData(userBo).enqueue(new MyCallback<NewsBaseEntity>(NewsMineInfoActivity.this) {
            @Override
            protected void onSuccess(Response<NewsBaseEntity> response) {
                try {
                    if ("1".equals(response.body().getCode())) {
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    //上传图片
    public void upLoadFile(File file, Bitmap bm) {
        Dialog dialog = new CenterDialog(R.layout.loading_layout, NewsMineInfoActivity.this).showLoad("正在上传图片...");
        try {
            String userId = SPUtils.get(App.getContext(), "userId", "") + "";
            RequestBody requestFile =
                    RequestBody.create(MediaType.parse("image/jpg"), file);
            MultipartBody.Part body =
                    MultipartBody.Part.createFormData("file", file.getName(), requestFile);
            Task.getApiService().modifyHead(userId, body).enqueue(new MyCallback<NewsBaseEntity>(NewsMineInfoActivity.this) {
                @Override
                protected void onSuccess(Response<NewsBaseEntity> response) {
                    dialog.dismiss();
                    NewsToastUtils.showToast(NewsMineInfoActivity.this, response.body().getMsg());
                    if ("1".equals(response.body().getCode())) {
                        String jsonStr = JSONObject.toJSONString(response.body().getData());
                        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                        String serverUrl = jsonObject.getString("serverUrl");
                        roundedImageView.setImageBitmap(bm);
                        insertData(serverUrl);
                    }
                }

                @Override
                protected void onFailure(Throwable t) {
                    dialog.dismiss();
                    NewsToastUtils.showToast(NewsMineInfoActivity.this, "连接超时！");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            dialog.dismiss();
        }

    }
}
